    # -*- coding: utf-8 -*-
    # this file is released under public domain and you can use without limitations

    #########################################################################
    ## This is a samples controller
    ## - index is the default action of any application
    ## - user is required for authentication and authorization
    ## - download is for downloading files uploaded in the db (does streaming)
    ## - call exposes all registered services (none by default)
    #########################################################################

if 0:
    import gluon
    global cache; cache = gluon.cache.Cache()
    global LOAD; LOAD  = gluon.compileapp.LoadFactory()
    global request; request = gluon.globals.Request()
    global response; response = gluon.globals.Response()
    global session; session = gluon.globals.Session()
    from gluon.sql import DAL
    global db; db = DAL()
    from gluon.tools import  Auth
    global auth; auth = Auth()
    from gluon.tools import Crud
    global crud; crud = Crud()
    from gluon.tools import Mail
    global mail; mail = Mail()
    from gluon.tools import PluginManager
    global plugins; plugins = PluginManager()
    from gluon.tools import Service
    global service; service = Service()



def index():
    """
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html
    """
    return dict(host=request.env.http_host)

def user():
    """
    exposes:
    http://..../[app]/default/user/login
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
    @auth.requires_membership('group name')
    @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())


def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    return service()


def list_data():
    from datetime import date
    response.generic_patterns = ['*']
    #test_data = {"name":"root" , "children" : [{"name": "Dates", "children": [{"name": "Sunday"}, {"name": "Monday"}, {"name": "Tuesday"}]}]}
    json_list = {"name":"Filters" , "children" : [{"name" : "All"},{"name" : "Dates" , "children" : None}]}
    vals= []
    for r in db( db.sale.id>0 ).select( db.sale.date,distinct=True):
        vals.append( {"name" :r.date} )

    if  vals:
        if (vals[-1]['name'] != date.today()):
            vals.append({"name" : date.today().isoformat()})
        else:
            json_list['children'][1]["children"] = vals
            return json_list
    else:
        vals = [{"name" : date.today().isoformat()}]

    json_list['children'][1]["children"] = vals
    return  json_list

def total_rows():
    response.generic_patterns = ['json']
    filter_str = request.vars.query
    if not filter_str or filter_str == "All" :

        query=(db.sale.id>0)
    else:
        query = (db.sale.date==filter_str)


    return  db(query).count()




def get_rows():
    response.generic_patterns = ['json']
    results = []
    filter_str = request.vars.query
    if request.env.web2py_runtime_gae:
        results=_gae_rows(filter_str)
    else:
        results=_normal_rows(filter_str)


    return  response.json(results)


def get_totals():
    response.generic_patterns = ['json']
    filter_str = request.vars.query
    if request.env.web2py_runtime_gae:
#        results=_get_gae_totals(filter_str)
        results=_get_gae_totals(filter_str)
    else:
        results=_get_totals(filter_str)
    return results


def total_item_rows():
    response.generic_patterns = ['json']
    query=(db.item.id>0)


    return  db(query).count()

def get_item_rows():
    response.generic_patterns = ['json']
    results = []
    query=query=(db.item.id>0)
    rows = db(query).select(db.item.id,db.item.name,db.item.base_price,db.item.price)

    for r in rows:
        items=r.as_dict()
        results.append(items)

    return  response.json(results)


def get_items():

    response.generic_patterns = ['json']
    query=(db.item.id>=0)
    items=db(query).select(db.item.id,db.item.name)
    return response.json(items)



def insert_sales():
    response.generic_patterns = ['json']
    food=request.vars.food_id
    amount=request.vars.amnt
    try:
        db.sale.insert(id_items = food , total_items = amount)
        return dict(status="success")
    except:
        import traceback
        return dict(status=traceback.format_exc())

def insert_items():
    response.generic_patterns = ['json']
    food=request.vars.food_name
    price=request.vars.price
    base_price=request.vars.base_price

    try:
        db.item.insert(name = food , price = price , base_price = base_price)
        return dict(status="success")
    except:
        import traceback
        return dict(status=traceback.format_exc())

#@auth.requires_signature()
#def data():
#    """
#    http://..../[app]/default/data/tables
#    http://..../[app]/default/data/create/[table]
#    http://..../[app]/default/data/read/[table]/[id]
#    http://..../[app]/default/data/update/[table]/[id]
#    http://..../[app]/default/data/delete/[table]/[id[
#    http://..../[app]/default/data/select/[table]
#    http://..../[app]/default/data/search/[table]
#    but URLs bust be signed, i.e. linked with
#    A('table',_href=URL('data/tables',user_signature=True))
#    or with the signed load operator
#    LOAD('default','data.load',args='tables',ajax=True,user_signature=True)
#    """
#    return dict(form=crud())

def _normal_rows(filter_str):
    results = []
    if not filter_str or filter_str == "All" :

        query=(db.item.id==db.sale.id_items)
    else:
        query = (db.item.id==db.sale.id_items) & (db.sale.date==filter_str)

    rows = db(query).select(db.sale.id,db.item.name,db.item.base_price,db.sale.date,db.sale.sale_time,db.item.price,db.sale.total_items)
#    items= {}
    for r in rows:
        items=r.item.as_dict()
        items.update(r.sale.as_dict())
        total_price = r.item.price * r.sale.total_items
        total_cost = r.item.base_price * r.sale.total_items
        calculated={"total_price" : total_price ,"total_cost" : total_cost ,"profit" : total_price - total_cost }
        items.update(calculated)
        results.append(items)
    return results


def _gae_rows(filter_str):
    results = []
    if not filter_str or filter_str == "All" :

        sale_query=(db.sale.id>=0)
        item_query = (db.item.id>=0)
    else:
        sale_query = (db.sale.date==filter_str)
        item_query = (db.item.id>=0)



    sales = db(sale_query).select(db.sale.id,db.sale.id_items,db.sale.total_items,db.sale.date,db.sale.sale_time)
    items = db(item_query).select(db.item.id,db.item.name,db.item.base_price,db.item.price)
    items_dict = {}

    for itm in items:
        items_dict[itm.id] = {'name':itm.name,'price' : itm.price,'base_price' : itm.base_price}


    for r in sales:
        sales_dict=r.as_dict()
        sales_dict.update(items_dict[r.id_items])
        total_price = items_dict[r.id_items]['price'] * r.total_items
        total_cost =  items_dict[r.id_items]['base_price'] * r.total_items
        calculated={"total_price" : total_price ,"total_cost" : total_cost ,"profit" : total_price - total_cost }
        sales_dict.update(calculated)
        results.append(sales_dict)
    return results

def _get_gae_totals(filter_str):
    total_price = 0
    total_cost = 0
    total_items = 0
    if not filter_str or filter_str == "All" :

        sale_query=(db.sale.id>=0)
        item_query = (db.item.id>=0)
    else:
        sale_query = (db.sale.date==filter_str)
        item_query = (db.item.id>=0)



    sales = db(sale_query).select(db.sale.id_items,db.sale.total_items,db.sale.date)
    items = db(item_query).select(db.item.id,db.item.name,db.item.base_price,db.item.price)
    items_dict = {}

    for itm in items:
        items_dict[itm.id] = {'name':itm.name,'price' : itm.price,'base_price' : itm.base_price}


    for r in sales:

        total_price += items_dict[r.id_items]['price'] * r.total_items
        total_cost +=  items_dict[r.id_items]['base_price'] * r.total_items
        total_items += r.total_items
    profit =  total_price - total_cost
    return dict(total_price = str(total_price) , total_profit = str(profit) , total_items = str(total_items))

def _get_totals(filter_str):
    response.generic_patterns = ['json']
    query=(db.item.id==db.sale.id_items)
    total_price = 0
    total_cost = 0
    total_items = 0
    if not filter_str or filter_str == "All" :

        query=(db.item.id==db.sale.id_items)
    else:
        query = (db.item.id==db.sale.id_items) & (db.sale.date==filter_str)
    rows = db(query).select(db.item.base_price,db.item.price,db.sale.total_items)
    for r in rows:
        total_price += r.item.price * r.sale.total_items
        total_cost += r.item.base_price * r.sale.total_items
        total_items += r.sale.total_items
    profit =  total_price - total_cost

    return dict(total_price = str(total_price) , total_profit = str(profit) , total_items = str(total_items))
